package com.ciei.dpagm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

/**
 * @author pp
 * @date 2022/02/21
 */
public class IdcpApiUtils {

    /**
     * 采集平台免登陆认证Token
     */
    private static final String AUTHORIZED_TOKEN = "F42F8AFE22CD550BF2A5B53735482B1F";

    /**
     * 设置免登陆认证Header
     * @param headers   请求头
     * @return          请求头
     */
    private static Map<String, String> setAuthorizedTokenHeader(Map<String, String> headers) {
        if (headers == null) {
            headers = new HashMap<>(2);
        }
        headers.put("Authorized-Token", AUTHORIZED_TOKEN);
        return headers;
    }

    /**
     * Post请求
     * @param url       url 链接
     * @param data      数据
     * @return
     */
    public static JSONObject doPost(@NotNull String url, @NotNull JSON data) {
        return doPost(url, data, null);
    }

    /**
     * Post请求
     * @param url       url 链接
     * @param data      数据
     * @param headers   请求头
     * @return
     */
    public static JSONObject doPost(@NotNull String url, @NotNull JSON data, Map<String, String> headers) {
        headers = setAuthorizedTokenHeader(headers);
        String response = HttpUtils.doPost(url, data, headers);
        return JSONObject.parseObject(response);
    }

    /**
     * Get请求
     * @param url       url 链接
     * @return
     */
    public static JSONObject doGet(@NotNull String url) {
        return doGet(url, null);
    }

    /**
     * Get请求
     * @param url       url 链接
     * @param headers   请求头
     * @return
     */
    public static JSONObject doGet(@NotNull String url, Map<String, String> headers) {
        headers = setAuthorizedTokenHeader(headers);
        String response = HttpUtils.doGet(url, headers);
        return JSONObject.parseObject(response);
    }
}
